<template>
  <div class="bg">
    <el-row>
      <el-col :span="4" :offset="8">
        <p>
          <el-button
            type="primary"
            style="
              background-color: #0d9c98;
              border-color: #0d9c98;
              width: 150px;
            "
            class="buttonSet2 buttonFontSize"
            @click="toWrite"
            >我要写信</el-button
          >
        </p>
      </el-col>
      <el-col :span="4">
        <p>
          <el-button
            type="primary"
            style="background-color: #0d4d9c; border-color: #0d4d9c"
            @click="toList"
            class="buttonSet2 buttonFontSize"
          >
            查看信件列表
            <span style="color: #dcca16">({{ mail_count }}条)</span>
          </el-button>
        </p>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form ref="ruleForm" label-width="150px">
          <el-form-item>
            <span style="color: #f19d6f" class="textFontSize"
              >*请您在下方框中输入意见或建议，投诉等，字数控制在10个字以上，1000字以内。</span
            >
          </el-form-item>
          <el-form-item>
            <template #label>
              <span class="textFontSize">问题内容:</span>
            </template>

            <!-- 20201010 添加富文本编辑器 -->
            <div id="wangEditorElement"></div>
            <!-- <el-input
              type="textarea"
              placeholder="请在此输入您的正文内容..."
              v-model="content"
              maxlength="1000"
              :autosize="{ minRows: 6, maxRows: 12 }"
              show-word-limit
            ></el-input> -->
          </el-form-item>
          <!--accept="" .docx,image/*,video/*,audio/*,text/plain,.pdf,.csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet -->
          <!-- <el-form-item label="附件:">
          <input id="upload_file" type="file" multiple @change="v_upload_files" />
          </el-form-item>-->

          <el-form-item>
            <template #label>
              <span class="textFontSize">附件:</span>
            </template>
            <el-upload
              class="upload-demo"
              ref="upload"
              multiple
              action
              :show-file-list="false"
              :on-change="handleChange"
              :file-list="fileList"
              :auto-upload="false"
              accept=".pdf,.doc,.docx,.xlsx,.xls,.ppt,.pptx,.png,.jpg,.jpeg,.wps,.txt,.wmv,.mov,.avi,.wm,.mp3,.wav"
            >
              <el-button
                slot="trigger"
                size="small"
                type="primary"
                style="
                  background-color: #a2b2be;
                  color: white;
                  border-color: #a2b2be;
                "
                class="buttonSet2 buttonFontSize"
                >选取文件</el-button
              >
              <div
                slot="tip"
                class="el-upload__tip"
                v-for="file in this.fileList"
                :key="file.uid"
              >
                {{ file.name }}
                <i
                  @click="deleteFile(file)"
                  style="margin-left: 20px"
                  class="el-icon-delete"
                ></i>
              </div>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <span style="color: #9f9f9f" class="textFontSize"
              >*（支持上传ppt，excel，word，pdf，图片格式的附件，文件大小低于50兆）</span
            >
          </el-form-item>

          <el-form-item>
            <template #label>
              <span class="textFontSize">是否匿名发布:</span>
            </template>
            <el-radio v-model="is_anonymous" label="0"
              ><span class="textFontSize">是</span></el-radio
            >
            <el-radio v-model="is_anonymous" label="1"
              ><span class="textFontSize">否</span></el-radio
            >
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="3" :offset="9">
        <p>
          <el-button
            type="primary"
            style="background-color: #0e4d9d; border-color: #0e4d9d"
            @click="submit()"
            v-loading.fullscreen.lock="fullscreenLoading"
            class="buttonSet2 buttonFontSize"
            >提交</el-button
          >
        </p>
      </el-col>
      <el-col :span="3">
        <p>
          <el-button
            type="primary"
            style="background-color: #a1b3bf; border-color: #a1b3bf"
            class="buttonSet2 buttonFontSize"
            @click="reset()"
            >取消</el-button
          >
        </p>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Api } from "../api/api_config";
import E from "wangeditor";

export default {
  data() {
    return {
      content: "",
      is_anonymous: "1",
      formData: "",
      empId: "",
      fullscreenLoading: false,
      fileList: [],
      mail_count: 0,
      file_size: 0,
      filterExt: [
        "pdf",
        "doc",
        "docx",
        "xlsx",
        "xls",
        "ppt",
        "pptx",
        "png",
        "jpg",
        "jpeg",
        "wps",
        "txt",
        "wmv",
        "mov",
        "avi",
        "wm",
        "mp3",
        "wav",
      ],
      editor: {},
    };
  },
  created() {
    this.initData();
  },
  mounted() {
    this.editor = new E("#wangEditorElement");
    this.editor.config.menus = [
      "head",
      "bold",
      "fontSize",
      "italic",
      "underline",
      "strikeThrough",
      "indent",
      "lineHeight",
      "foreColor",
      "backColor",
      "link",
      "list",
      "justify",
      "splitLine",
      "undo",
      "redo",
    ];
    this.editor.create();
  },
  methods: {
    initData() {
      if (this.$store.state.empId === "") {
        // 获取empId
        let url = window.location.href
        let cs = url.split("?")[1]

        if (cs !== undefined) {
          let empId = cs.split("=")[1]
          if (empId !== undefined) {
            // 获取参数，传入state
            this.$store.state.empId = empId;
          } else {
            this.$message.error("未能正常获取参数，请关闭后重试。")
          }
        } else {
          this.$message.error("未能正常获取参数，请关闭后重试。")
        }
      }

      this.empId = this.$store.state.empId
      this.formData = new FormData()

      // 获取文件总count
      this.queryMails();
    },
    v_upload_files(e) {
      let files = e.target.files
      this.formData = new FormData()
      for (let i = 0; i < files.length; i++) {
        this.formData.append("files", files[i])
      }
    },
    submit() {
      this.content = this.editor.txt.html();
      let text = this.content.replace(/<[^<>]+>/g,"");
      if (text.length <= 10) {
        this.$message({
          message: "您提交的信息太少，请至少输入10个字，详细描述后提交",
          type: "warning",
        });
        return;
      }
      if (text.length > 1000) {
        this.$message({
          message: "您提交文字内容已经大于1000字，请检查后提交",
          type: "warning",
        });
        return;
      }
      this.formData = new FormData();
      for (let i = 0; i < this.fileList.length; i++) {
        this.formData.append("files", this.fileList[i].raw)
      }
      this.formData.append("content", this.content)
      let that = this;
      this.fullscreenLoading = true;
      let url =
        Api.all.newMail +
        "?isAnonymous=" +
        this.is_anonymous +
        "&senderEmpId=" +
        this.empId;
      this.$axios
        .post(url, this.formData)
        .then(function (response) {
          that.$message({
            message: "提交信息成功",
            type: "success",
          });
          // that.reset();
          that.toList()
          that.fullscreenLoading = false;
        })
        .catch(function (error) {
          console.log(error)
          that.$message.error("数据有误")
          that.fullscreenLoading = false
        });
    },
    reset() {
      this.content = ""
      this.is_anonymous = "1"
      this.$refs.upload.clearFiles()
      this.fileList = []
      // window.parent.closeWindow()
      window.parent.postMessage("close",'*')
    },
    handleChange(file, fileList) {
      // 判断文件不能大于50M
      let isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        this.$message({
          message: "您提交的文件太大，文件不能高于50M，请重新选择附件。",
          type: "warning",
        });
        return;
      }

      // 判断文件类型
      let ext = file.name.substring(file.name.lastIndexOf(".") + 1);
      let isAllowExt = false;
      this.filterExt.forEach((element) => {
        if (element === ext) {
          isAllowExt = true;
        }
      });

      if (!isAllowExt) {
        this.$message({
          message: "您提交的文件不在允许的范围内。",
          type: "warning",
        });
        return;
      }

      let isOverMax = this.file_size + file.size > 1024 * 1024 * 100;
      if (isOverMax) {
        this.$message({
          message: "您提交的文件一共大小超过了100M，请重新选择附件。",
          type: "warning",
        });
        return;
      }
      if (file !== null || file !== undefined) {
        this.file_size = this.file_size + file.size;
        this.fileList.push(file);
      }
    },
    deleteFile(item) {
      this.fileList.splice(
        this.fileList.findIndex((e) => e.uid === item.uid),
        1
      );
      this.file_size = this.file_size - item.size;
    },
    toWrite() {
      this.$router.push("/newMail");
    },
    toList() {
      this.$router.push("/mailList");
    },
    queryMails() {
      // 拼接查询参数
      let url = Api.all.queryMails;
      url += "?empId=" + this.empId;
      url += "&mailboxStatusFlag=104";
      url += "&pageNum=" + 1;
      url += "&pageSize=" + 5;
      // url += "&isPc=true";
      let that = this;
      this.$axios
        .post(url)
        .then(function (response) {
          if (response.data !== null) {
            that.mail_count = response.data.data.totalCount;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};
</script>

<style scoped>
.bg {
  filter: progid:DXImageTransform.Microsoft.Shadow(color=#909090,direction=120,strength=4); /*ie*/
  -moz-box-shadow: 2px 2px 10px #909090; /*firefox*/
  -webkit-box-shadow: 2px 2px 10px #909090; /*safari或chrome*/
  box-shadow: 2px 2px 10px #909090; /*opera或ie9*/
  border: 1px soild #ccc;
  border-radius: 10px;
  -webkit-border-radius: 9px;
  -moz-border-radius: 9px;
  background-color: white;
  padding: 10px 10px 10px 10px;
}
</style>
